import { Component, OnInit, Output, EventEmitter, Input, SimpleChanges,HostListener } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';

import { ClueDataService } from '../../../../../@core/service/clue-service/clue-data.service';
import { Router,ActivatedRoute } from '@angular/router';
import { ClueService } from '../../../../../@core/service/typescript-angular-client/api/clue.service';
import { DocgenService} from '../../../../../@core/service/case-review/doc-select/api/docgen.service'
import {CaseReviewService} from '../../../../../@core/service/case-review/case-review.service'
import { NzFormatEmitEvent } from 'ng-zorro-antd/core';

import { OrgService } from '../../../../../@core/service/person-select-service/api/org.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import {SYSTEMService} from '../../../../../@core/service/login-service/api/sYSTEM.service';
import { BizfileService } from '../../../../../@core/service/case-review/doc-service/api/bizfile.service'
@Component({ 
  selector: 'app-full-staff',
  templateUrl: './full-staff.component.html',
  styleUrls: ['./full-staff.component.scss'],
  animations: [
    trigger('expandShrink', [
      state('expand', style({
        height: '233px',
        // opacity: 1
      })),
      state('shrink', style({
        height: '10px', 
        // opacity: 0.5
      })),
      transition('shrink => expand', [
        animate('0.2s')
      ]),
      transition('expand => shrink', [
        animate('0.2s')
      ]),
    ])
  ]
})
export class FullStaffComponent implements OnInit {

  @Output('expandAnimationFlag') expandAnimation = new EventEmitter<any>();
  @Input() name: any; 
  @Output() senddoc = new EventEmitter()
  @Output() sendFather = new EventEmitter()
  @Input() clueList:any;
  @Input() clueDoc:any;
  @Input() isExpand:boolean;

  //案件审批
  @Output() approvalReview = new EventEmitter() 
  constructor(
    public systemService:SYSTEMService,
    public message:NzMessageService,
    public docgen:DocgenService,
    public orgService: OrgService,
    public clueData:ClueDataService,
    public router:Router,
    public active:ActivatedRoute,
    public clue:ClueService,
    public caseReview:CaseReviewService,
    public bizFileService:BizfileService) { 
   
  }
  //选中文书
  public DocumentId:string;
  //返回文书列表
  public DocumentList:any[];
  public session = sessionStorage;
  public dataList:any;
  public id:any;
  public remark:any;
  public approvalFull:any = "提交线索";//办理事项
  public v1:any;
  public v2:any;
  public sessionDepart:any = JSON.parse(window.sessionStorage.getItem('organizations'))[0];
  public selectCode:any;
  public getRoleNameList:any[]=[];//获取人员角色名称List
  public getRoleName:any=null;//获取人员角色名称
  public pertmentId:string;//当前登录人的部门ID
  expandKeys = ['0-0'];  // 默认展开的节点
  value: string;
  nodes = []; 
  listOfOption:any; 
  personOptionList = [];
  getPersonSelectedValue = [];
  selectedValue:any;
  selectedPersonValue:any;
  public selectPersonCode:any;

  onExpandChange(e: Required<NzFormatEmitEvent>): void {
    const node = e.node;
    if (node && node.getChildren().length === 0 && node.isExpanded) {
      this.loadNode(node['origin']['value']).then(data => {
        node.addChildren(data);
      });
    }
  }
  // 加载节点
  loadNode(parentId): Promise<any[]> {
    return new Promise(resolve => {
      setTimeout(
        () => {
          let nodesData = JSON.parse(this.session.getItem('areaData'));
          resolve(this.DataProcess(nodesData, parentId, '机构'))
        },
        500
      );
    });
  }
  // 默认选中机构 部门
getSelectedNodeList(key,callback): void {
    this.systemService.authOrgDeptsOrgIdGet(key).subscribe(res => {
      if (res['rel']) {
        this.listOfOption = res['data'];
      }
      callback && callback( this.listOfOption)
    }, error => {
    });
   
}
//切换机构查询部门和人员
getSelectedNodeLists(key){
    this.selectCode = null;
    this.selectPersonCode = null;
    this.systemService.authOrgDeptsOrgIdGet(key).subscribe(res => {
      if (res['rel']) {
        this.listOfOption = res['data'];
        this.selectCode = res['data'][0]['deptId'];
        this.selectedValue = res['data'][0]['deptId'];
        this.getPerson(res['data'][0]['deptId']);
      }
      // callback && callback( this.listOfOption)
    }, error => {
    });
   
}
  ngOnInit() {
    //初始化获取文书列表
    this.docgen.docgenAllFiletypeGet().subscribe(data=>{
      this.DocumentList = data;
    })
    this.id = this.active.snapshot.params["id"];
    let nodesData = JSON.parse(this.session.getItem('areaData'));
    this.nodes = this.DataProcess(nodesData, '0', '机构');
    // 登记机关赋值
    for (let index = 0; index < this.sessionDepart.length; index++) {
      if(this.sessionDepart[index].orgTypeName=="机构"){
        this.value = this.sessionDepart[index].orgId;
        this.v2 = this.sessionDepart[index].orgId;
        this.v1 = this.sessionDepart[index].areaParentId;
        this.expandKeys = [this.v1,this.v2]

       this.getSelectedNodeList(this.sessionDepart[index].orgId,(data)=>{
          this.listOfOption = data;
           for (let i = 0; i < this.sessionDepart.length; i++) {
             if(this.sessionDepart[i].orgTypeName=="部门"){
               
               for(let z = 0;z < this.listOfOption.length;z++){
                 if(this.listOfOption[z].deptId==this.sessionDepart[i].orgId){
                    this.selectCode = this.listOfOption[z].deptId;
                    this.selectedValue = this.listOfOption[z].deptId;
                    this.getPerson(this.listOfOption[z].deptId);
                 }else{
                    this.selectCode = this.listOfOption[0].deptId;
                    this.selectedValue = this.listOfOption[0].deptId;
                    this.getPerson(this.listOfOption[0].deptId);
                 }
               }
             }
           }
       });
      } 
      else if(this.sessionDepart[index].orgTypeName=="部门"){
          
          this.pertmentId = this.sessionDepart[index].orgId;
         
      }
    }
  }

  getSelectedValue(e){
    if(e){
      this.selectPersonCode = null;
      this.selectedValue = e; 
          // this.selectedValue = value[0].key;
      let token = this.session.getItem("accessToken") || "";
      for (let i = 0; i < this.listOfOption.length; i++) {
        if (this.listOfOption[i]['deptId'] == e) {
          this.pertmentId = this.listOfOption[i]['deptId'];
          this.getPerson( this.listOfOption[i]['deptId']);
        }
      }
    }
  }


  // 获取部门下人员信息
  getPerson (deptId) {
    this.systemService.authDeptUsersDeptIdGet(deptId).subscribe((data) => {
      if (data['rel'] == true) {
        this.personOptionList=[];
        for (let i = 0; i < data['data'].length; i++) {
          let obj = {'realName': '','positionCode': '','userId':"",'role':""};
          obj.realName = data['data'][i]['realName'] || "";
          obj.positionCode = data['data'][i]['positionCode'] || "";
          obj.userId = data['data'][i]['userId'] || "";
          obj.role = data['data'][i]['role'] || "";
          this.personOptionList.push(obj);
        }
        let kezhang=data['data'].filter(item=>item['positions'][0]["positionName"]=='科长')[0];
        if(kezhang){
            this.selectPersonCode = kezhang["userId"];
            const myRoleList= kezhang['roles'];
            for(let m =0;m<myRoleList.length;m++){
              if(m==0){
                this.getRoleName = myRoleList[m].roleName;
              }else{
                this.getRoleName +=','+ myRoleList[m].roleName;
              }
            }
        }else{
            this.selectPersonCode=data['data'][0]["userId"];
            const myRoleList= data['data'][0]['roles'];
            for(let m =0;m<myRoleList.length;m++){
              if(m==0){
                this.getRoleName = myRoleList[m].roleName;
              }else{
                this.getRoleName +=','+ myRoleList[m].roleName;
              }
            }
        }
      }
    }, (error) => {
    })
  }
  getRoleNameMethods(e){
    let personOptionList = this.personOptionList;
    for(let i =0; i<personOptionList.length;i++){
      if(personOptionList[i].userId == e){
        this.getRoleNameList = personOptionList[i].role;
      }
    }
  }

  // 将后台返回的数据处理成符合树形结构 
  DataProcess(data, parentId, type) {
    let arrayList = [];
    for(var i = 0; i < data.length; i++) {
      if (data[i]['orgTypeName'] == type && data[i]['orgParentId'] == parentId) {
        let obj = {
          'title': '', 
          'text': '',
          'value': '', 
          'key': '', 
          'parentId': '', 
          'children': []
        };
        obj.title = data[i]['orgName'] || "";
        obj.text = data[i]['orgName'] || "";
        obj.value = data[i]['orgId'] || "";
        obj.key = data[i]['orgId'] || "";
        obj.parentId = data[i]['orgParentId'] || "";
        obj.children = this.DataProcess(data, obj.value, '机构');
        if (obj.children.length <= 0) {
          obj['isLeaf'] = true;
        }
        arrayList.push(obj);
      }
    }
    return arrayList;
  }

  ngOnChanges(changes: SimpleChanges): void {
    if(changes.clueList){
      if(changes.clueList.currentValue && JSON.stringify(changes.clueList.currentValue) != "{}"){
        this.clueList =  changes.clueList.currentValue;
        this.dataList = JSON.parse(this.clueList.clueDoc).data
      }
    }else if(changes.clueDoc){
      if(changes.clueDoc.currentValue){
        this.clueList =  this.clueDoc;
        this.dataList = JSON.parse(this.clueList.clueDoc).data
      }
    }
  }
 
  mysubmit(){
    // 线索新增编辑选择人员
    if(this.name =="addclue"){
      this.message.create('error', '请先保存并生成文书');
      return false
    }else{
    if(this.getRoleNameList){
          for(let i=0;i<this.getRoleNameList.length;i++){
            if(i == 0){
              this.getRoleName += this.getRoleNameList[i].roleName;
            }else{
              this.getRoleName+=','+this.getRoleNameList[i].roleName;
            }
          }
      }

      this.clueList.caseUserType = this.getRoleName;//用户角色
      this.clueList.caseSerial = "1";//用户角色序号
      this.clueList.partySector = this.pertmentId;//当前登录人的部门ID
      this.clueList.clueStatus = '03' 
      if(typeof(this.clueList['address'])!="string"){
        this.clueList['address'] = JSON.stringify(this.clueList['address'])
      }
      if(typeof(this.clueList['caseProvider'] ) !="string"){
        this.clueList['caseProvider'] = JSON.stringify(this.clueList['caseProvider'])
      }

      this.clueList['id'] = this.active.snapshot.params['id']
      this.clueList.casePartyPerson= this.selectPersonCode;
      this.clueList.casePartyDepart = this.value;
      this.clueList.casePartySector = this.selectedValue;
      this.clueList.caseRemarks = this.remark;
      this.clueList.partyItem = this.approvalFull;
      this.clueList.updateUser =this.session.getItem('userId');
      this.clueList.partyPerson =this.session.getItem('realName');
      this.clueList.partyPersonId =this.session.getItem('userId');
      // this.clueList.registerDepartName = 
      if(typeof(this.clueList)=="string"){
        return false
      }else{
        this.clueList = JSON.stringify(this.clueList);
      }

      this.clue.updateClue(this.clueList).subscribe(list=>{
        this.clueList = JSON.parse(this.clueList);
        if(list.code=="200"){
          this.router.navigate(['/main/home/clue']);
        }else{
          this.message.create('error', '提交失败');
          //没什么用
          this.clueList.address = JSON.parse(this.clueList.address);
          this.clueList.caseProvider = JSON.parse(this.clueList.caseProvider);
        }
      })
    }
  }

  back(){
    this.router.navigate(['/main/home/clue']);
  }

  // 下载文件
  download(fileid,fileName) {
      this.bizFileService.downloadFile(fileid).subscribe((res:any) => {
        this.createA2Click(res,fileName)
      }, (error) => { 
        this.message.create('error','文书下载失败！')
      });
  }

  createA2Click(res,fileName){
    const fileURL = URL.createObjectURL(res);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.download = fileName;
    a.href = fileURL;
    a.click();
  }

  //审批事件
  approval(docid,doctype):void{
    this.caseReview.setShowWindow(true);
    this.caseReview.getCreateCaseDoc().emit({condition:'Approval',docid,doctype});
  }

  //新建文书
  newDocuments(){
    if(this.DocumentId){ 
      this.caseReview.setShowWindow(true);
      this.caseReview.getCreateCaseDoc().emit({condition:'New',docid:null,doctype:this.DocumentId});
    }
  }

  //文书选择列表
  docSelect(event){

  }

  // 底部卡片展开与收起
  cardToggle() {
    this.isExpand = !this.isExpand;
    this.expandAnimation.emit(this.isExpand);
  }
  // 关闭卡片
  closeCard(){
    this.isExpand  = false;
    this.expandAnimation.emit(this.isExpand);
  }
  // 打开卡片
  openCard(){
    this.isExpand = true;
    this.expandAnimation.emit(this.isExpand);
  }
}
